<!-- @format -->

<template>
  <view class="red-flower">
    <wd-navbar fixed placeholder safeAreaInsetTop>
      <template #left>
        <view class="nav-left">
          <the-capsule></the-capsule>
          <!-- 用户列表 -->
          <the-users
            :users="users"
            :current-user="currentUser"
            @change="toSwitchUser"
            @add="onAddUser"
          ></the-users>
        </view>
      </template>
    </wd-navbar>

    <!-- 统计面板 -->
    <view class="stats-panel">
      <view class="stat-item">
        <view class="stat-tip">预测日期：</view>
        <view class="stat-value">{{ available }}</view>
      </view>

      <!-- 操作按钮 -->
      <view class="action-buttons">
        <the-icon-btn
          title="已标记"
          @click="showLogDialog"
          bgColor="pink"
          icon="gift"
        />
      </view>
    </view>

    <view class="calendar-container">
      <wd-calendar-view
        ref="calendarRef"
        v-model="selectedDate"
        :max-date="maxDate"
        :formatter="formatter"
      >
      </wd-calendar-view>
    </view>

    <view class="record-x">
      <!-- 消息说明 -->

      <view class="record-append-x">
        <view class="label-x">
          <view class="label-title">备注：</view>
          <view v-if="currentHasTag" class="label-mark">{{
            currentTag.mark
          }}</view>
          <input v-else class="label-input" type="text" v-model="markText" />
        </view>
        <view class="record-opes">
          <the-icon-btn
            v-if="currentHasTag"
            bgColor="pink"
            icon="edit"
            @click="onClear"
            title="清除"
          >
          </the-icon-btn>
          <the-icon-btn
            v-else
            bgColor="pink"
            icon="edit"
            @click="onRecord"
            title="标记"
          >
          </the-icon-btn>
        </view>
      </view>
    </view>

    <!-- 日志弹窗 -->
    <wd-popup v-model="showLog" position="bottom">
      <view class="dialog-title">标记记录</view>
      <scroll-view class="log-list" scroll-y>
        <view v-if="!tagLogs.length" class="tip-empty">-- 暂无记录 --</view>
        <view
          v-else
          v-for="(log, index) in tagLogs"
          :key="index"
          class="log-item"
        >
          <view>{{ log.dateStr }} </view>
          <view class="log-item-info">{{ log.mark }}</view>
        </view>
      </scroll-view>
    </wd-popup>

    <wd-toast></wd-toast>
  </view>
</template>

<script setup>
import { computed, effect, onMounted, ref, watch } from 'vue'
import { useToast } from 'wot-design-uni'
import { useBigAunt } from '../../composables/useBigAunt'
import {
  formatDate,
  preventRepeatedClick,
  sortByDesc,
} from '../../utils/commonUtils'

const DAY_CONF = {
  max: 35,
  aver: 28,
  min: 20,
}

const toast = useToast()

const showLog = ref(false)

const calendarRef = ref(null)
const userSwitching = ref(false)

const markText = ref('')

const today = Date.now()
const selectedDate = ref(today)
const maxDate = ref(today)

const {
  users,
  currentUser,
  content,
  queryData,
  updateTag,

  addUser,
  changeUser,
  switchUser,
} = useBigAunt()

const formatter = (day) => {
  const [key, d] = formatDate(day.date, 'yyyyMM dd').split(' ')
  //
  const history = content.value[key]
  if (history && history[d]) {
    day.bottomInfo = '.'
  }

  return day
}

const tagLogs = computed(() => {
  // 将content对象 { ym: { day: {} }} 转换为数组 []
  const keys = sortByDesc(Object.keys(content.value || {}))
  const logs = keys
    .map((key) => {
      const history = content.value[key] || {}
      // 降序排序

      const days = sortByDesc(Object.keys(history))
      return days.map((day) => {
        const rest = history[day]
        rest.dateStr = formatDate(rest.date, 'yyyy-MM-dd')
        return rest
      })
    })
    .flat()
  return logs
})

const currentTag = computed(() => {
  const [key, day] = formatDate(selectedDate.value, 'yyyyMM dd').split(' ')
  const history = content.value[key] || {}
  return history[day]
})

const currentHasTag = computed(() => {
  return !!currentTag.value
})

const available = computed(() => {
  // 正在切换用户时，为0
  if (userSwitching.value) return '预测中...'

  const count = tagLogs.value.length
  if (count === 0) return '请标记最近的日期吧~'

  const firstItem = tagLogs.value[0]
  // 若只有一项，且距离今天小于30天，返回 +28 的日期
  const diff = today - firstItem.date
  const diffDays = diff / (1000 * 60 * 60 * 24)
  if (diffDays < DAY_CONF.max) {
    let intAverage = DAY_CONF.aver
    if (count > 1) {
      let circles = tagLogs.value.map((item, index, list) => {
        // 取得下一项，最后一项直接返回 0
        if (index === list.length - 1) return 0
        const nextItem = list[index + 1]
        const diff = item.date - nextItem.date
        return diff / (1000 * 60 * 60 * 24)
      })

      circles = circles.filter(
        (value) => value < DAY_CONF.max && value > DAY_CONF.min
      )

      if (circles.length) {
        // 取平均值
        const sum = circles.reduce((a, b) => a + b, 0)
        const average = sum / circles.length
        // 取平均值的整数部分
        intAverage = Math.floor(average)
      }
    }

    const date = firstItem.date + intAverage * 24 * 60 * 60 * 1000
    return formatDate(date, 'yyyy-MM-dd')
  } else {
    return '请标记最近的日期吧~'
  }
})

let change = 1
const refreshCalendar = () => {
  maxDate.value = today + change
  change = change * -1
}

watch(content, () => {
  refreshCalendar()
})

effect(() => {
  markText.value = ''
})

const initData = async () => {
  await queryData()
  toSwitchUser(users.value[0])
}

// 初始化加载本地数据
onMounted(() => {
  // 获取数据
  initData()
  // 滚动到当前日期
  calendarRef.value?.scrollIntoView()
})

const toSwitchUser = async (user) => {
  if (userSwitching.value) return

  userSwitching.value = true
  await switchUser(user)
  userSwitching.value = false
}

const showLogDialog = () => {
  showLog.value = true
}

const onAddUser = preventRepeatedClick(async (params) => {
  const { isAdd = false, userName = '', callback } = params || {}
  if (!userName) {
    toast.show('请输入名称')
    return
  }

  if (isAdd) {
    const data = await addUser(userName)
    toast.show('添加成功')

    callback && callback(false)

    await switchUser(data)
  } else {
    // 编辑
    await changeUser({ ...currentUser.value, name: userName })
    toast.show('操作成功')

    callback && callback(false)
  }
})

const onClear = preventRepeatedClick(async () => {
  if (!currentHasTag) return
  // 清除此次标记
  const [key, day] = formatDate(selectedDate.value, 'yyyyMM dd').split(' ')
  const history = content.value[key]
  if (!history) return

  delete history[day]
  await updateTag({
    [key]: history,
  })
  toast.show('操作成功')
})

const onRecord = preventRepeatedClick(async () => {
  // 按年月保存数据
  const [key, day] = formatDate(selectedDate.value, 'yyyyMM dd').split(' ')
  const history = content.value[key] || {}
  // 判断历史当月是否已经存在两条记录
  const length = Object.keys(history).length
  if (length >= 2) {
    toast.show('本月已经标记过两次啦~')
    return
  }

  history[day] = {
    mark: markText.value || '标记',
    date: selectedDate.value,
    update: Date.now(),
  }

  await updateTag({
    [key]: history,
  })

  toast.show('操作成功')
})
</script>

<style scoped lang="scss">
.mb-10 {
  margin-bottom: 20rpx;
}

.nav-left {
  display: flex;
  gap: 16rpx;
  align-items: center;
}

.calendar-day {
  position: relative;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.stats-panel {
  position: relative;
  margin: 40rpx;
  padding: 40rpx 20rpx;
  background: linear-gradient(135deg, #fff5f5, #fff);
  border-radius: 24rpx;
  box-shadow: 0 8rpx 24rpx rgba(229, 77, 66, 0.1);
  display: flex;
  /* justify-content: space-around; */
  align-items: flex-end;
  gap: 40rpx;
}

.user-setting {
  position: absolute;
  top: 8rpx;
  right: 8rpx;
}

.stat-item {
  padding: 20rpx 40rpx;
  min-width: 300rpx;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.stat-tip {
  font-size: 24rpx;
  margin-bottom: 8rpx;
  color: pink;
}

.stat-value {
  // 白色 粉红描边样式
  font-size: 40rpx;
  font-weight: bold;
  color: white;
  text-shadow: 0 0 4px red;
}

.action-buttons {
  // margin: 40rpx;

  display: flex;
  align-items: center;

  gap: 20rpx;
}

.action-buttons .wd-button {
  flex: 1;
  border-radius: 12rpx;
  padding: 24rpx 0;
  font-size: 28rpx;
}

.calendar-container {
  padding-bottom: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.record-x {
  // background-color: #f8f8f8;
  border-radius: 8rpx;
  margin: 20rpx;
  padding: 20rpx;
}
.record-append-x {
  padding: 8rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}
// .record-opes {
//   display: flex;
//   align-items: center;
//   justify-content: flex-start;
//   gap: 40rpx;
// }

.record-list-x {
  margin-top: 30rpx;
}

.record-title {
  text-align: center;

  color: #666;
  font-size: 28rpx;
}

.record-list-item {
  margin: 20rpx 0;
  display: flex;
  justify-content: space-between;
  font-size: 28rpx;
}

/* 修改记录和使用弹窗容器 */
.dialog-container {
  padding: 40rpx;
  padding-top: 280rpx;
  // padding-bottom: calc(40rpx + env(safe-area-inset-bottom)); /* 新增安全底部 */
  border-radius: 32rpx 32rpx 0 0;
}

.label-x {
  margin: 8rpx 0;
}

.label-title {
  font-size: 24rpx;
  color: #222;
  margin: 8rpx 0;
}

.label-mark {
  padding: 8rpx;
}

.label-input {
  border: 1px solid #ddd;
  padding: 8rpx;
}

:deep(.wd-month__day-bottom:not(:empty)) {
  text-align: center;
  color: red;
  font-weight: bold;
  font-size: 0;
  bottom: 4rpx;

  font-family: 'wd-icons';
  &::before {
    content: '\e6a9';
    font-size: 28rpx;
  }
}

/* 调整日志弹窗高度 */
.log-list {
  min-height: calc(60vh - env(safe-area-inset-bottom));
  width: 100%;
  padding: 20rpx 40rpx;
  box-sizing: border-box;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom)); /* 安全底部 */
}

.tip-empty {
  font-size: 24rpx;
  color: #333;
  text-align: center;
  margin: 80rpx 0;
}

.log-item {
  margin-bottom: 20rpx;
  padding-top: 4rpx;

  display: flex;
  justify-content: space-between;

  font-size: 28rpx;
}

.log-item-info {
  font-size: 24rpx;
  color: pink;
}

.dialog-title {
  font-size: 36rpx;
  font-weight: 500;
  text-align: center;
  padding: 20rpx 0;
}
.log-date {
  margin-top: 8rpx;
  font-size: 24rpx;
  color: #666;
}
</style>
